/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.web.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.monitor.utils.Achieve;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.web.entity.WxAgents;
import com.jeeplus.modules.web.entity.WxEquipmentAddress;
import com.jeeplus.modules.web.entity.YjEquipment;
import com.jeeplus.modules.web.mapper.WxAgentsMapper;
import com.jeeplus.modules.web.service.WxEquipmentAddressService;
import com.jeeplus.modules.web.service.YjEquipmentService;

/**
 * 设备信息Controller
 *
 * @author rongjie
 * @version 2017-08-06
 */
@Controller
@RequestMapping(value = "${adminPath}/web/yjEquipment")
public class YjEquipmentController extends BaseController {

	@Autowired
	private YjEquipmentService yjEquipmentService;
	@Autowired
	private WxEquipmentAddressService wxEquipmentAddressService;
	@Autowired
	private WxAgentsMapper wxAgentsMapper;

	@ModelAttribute
	public YjEquipment get(@RequestParam(required = false) String id) {
		YjEquipment entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = yjEquipmentService.get(id);
		}
		if (entity == null) {
			entity = new YjEquipment();
		}
		return entity;
	}

	/**
	 * 设备信息列表页面
	 */
	@RequiresPermissions("web:yjEquipment:list")
	@RequestMapping(value = { "list", "" })
	public String list(Integer pageIndex, Model model,YjEquipment yjEquipment) {
		if(pageIndex==null){
			pageIndex = 1;
		}
		model.addAttribute("pageIndex",pageIndex);
		model.addAttribute("yjEquipment",yjEquipment);
		return "modules/web/yjEquipmentList";
	}

	/**
	 * 设备信息列表数据 包括1.直接绑定于自己的设备，2.其下属代理或门店绑定的设备
	 */
	@ResponseBody
	@RequiresPermissions("web:yjEquipment:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(YjEquipment yjEquipment, HttpServletRequest request, HttpServletResponse response,
			Model model) {

		User currentUser = UserUtils.getUser();
		WxAgents wxAgents = new WxAgents();

		if (!currentUser.getId().equals("1")) {
			// wxAgents.setUserName(currentUser.getMobile());
			wxAgents = wxAgentsMapper.findUniqueByProperty("username", currentUser.getMobile());
			yjEquipment.setAgents(wxAgents);

		}

		Page<YjEquipment> page = yjEquipmentService.findPage(new Page<YjEquipment>(request, response), yjEquipment);
		return getBootstrapData(page);
	}

	/**
	 * 设备信息列表数据 包括1.直接绑定于自己的设备，2.其下属代理或门店绑定的设备
	 */
	@ResponseBody
	@RequiresPermissions("web:yjEquipment:list")
	@RequestMapping(value = "dataForBind")
	public Map<String, Object> dataForAgentBinding(YjEquipment yjEquipment, HttpServletRequest request,
			HttpServletResponse response, Model model) {

		User currentUser = UserUtils.getUser();
		WxAgents wxAgents = new WxAgents();

		if (!currentUser.getId().equals("1")) {
			// wxAgents.setUserName(currentUser.getMobile());
			wxAgents = wxAgentsMapper.findUniqueByProperty("username", currentUser.getMobile());
			yjEquipment.setAgents(wxAgents);
		}

		Page<YjEquipment> page = yjEquipmentService.findPage(new Page<YjEquipment>(request, response), yjEquipment);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑设备信息表单页面
	 */
	@RequiresPermissions(value = { "web:yjEquipment:view", "web:yjEquipment:add",
			"web:yjEquipment:edit" }, logical = Logical.OR)
	@RequestMapping(value = "form")
	public String form(YjEquipment yjEquipment, Model model,Integer pageIndex) {
		model.addAttribute("yjEquipment", yjEquipment);
		model.addAttribute("pageIndex", pageIndex);
		if (StringUtils.isBlank(yjEquipment.getId())) {// 如果ID是空为添加
			model.addAttribute("isAdd", true);
		}
		return "modules/web/yjEquipmentForm";
	}

	/**
	 * 保存设备信息
	 */
	@RequiresPermissions(value = { "web:yjEquipment:add", "web:yjEquipment:edit" }, logical = Logical.OR)
	@RequestMapping(value = "save")
	public String save(YjEquipment yjEquipment, Model model, RedirectAttributes redirectAttributes,Integer pageIndex) throws Exception {
		if(pageIndex==null){
			pageIndex = 1;
		}
		if (!beanValidator(model, yjEquipment)) {
			return form(yjEquipment, model,pageIndex);
		}
		if(StringUtils.isEmpty(yjEquipment.getId())){
            YjEquipment number = yjEquipmentService.findUniqueByProperty("number", yjEquipment.getNumber());
            if(number!=null){
                addMessage(model, "提交失败:设备编号重复");
                return form(yjEquipment, model,pageIndex);
            }
        }else{
            YjEquipment yjEquipments = yjEquipmentService.get(yjEquipment.getId());
            if (yjEquipment.getCity().equals(yjEquipments.getCity())) {
                WxEquipmentAddress wxEquipmentAddress = new WxEquipmentAddress();
                wxEquipmentAddress.setEquipment(yjEquipments);
                wxEquipmentAddress.setAddress(yjEquipment.getCity());
                wxEquipmentAddressService.save(wxEquipmentAddress);
            }
        }
//        if(StringUtils.isBlank(yjEquipment.getUrl())){
//			yjEquipment.setUrl(yjEquipmentService.saveQrCode(yjEquipment.getNumber()));
//		}
		yjEquipment.setUrl(Achieve.getUrl("1",yjEquipment.getNumber()));

		// 新增或编辑表单保存
		yjEquipmentService.save(yjEquipment);// 保存
		addMessage(redirectAttributes, "保存设备信息成功");
		return "redirect:" + Global.getAdminPath() + "/web/yjEquipment/?repage&pageIndex="+pageIndex;
	}

	/**
	 * 删除设备信息
	 */
	@ResponseBody
	@RequiresPermissions("web:yjEquipment:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(YjEquipment yjEquipment, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		yjEquipmentService.delete(yjEquipment);
		j.setMsg("删除设备信息成功");
		return j;
	}

	/**
	 * 批量删除设备信息
	 */
	@ResponseBody
	@RequiresPermissions("web:yjEquipment:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] = ids.split(",");
		for (String id : idArray) {
			yjEquipmentService.delete(yjEquipmentService.get(id));
		}
		j.setMsg("删除设备信息成功");
		return j;
	}

	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("web:yjEquipment:export")
	@RequestMapping(value = "export", method = RequestMethod.POST)
	public AjaxJson exportFile(YjEquipment yjEquipment, HttpServletRequest request, HttpServletResponse response,
			RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
			String fileName = "设备信息" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
			Page<YjEquipment> page = yjEquipmentService.findPage(new Page<YjEquipment>(request, response, -1),
					yjEquipment);
			new ExportExcel("设备信息", YjEquipment.class).setDataList(page.getList()).write(response, fileName).dispose();
			j.setSuccess(true);
			j.setMsg("导出成功！");
			return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出设备信息记录失败！失败信息：" + e.getMessage());
		}
		return j;
	}

	/**
	 * 导入Excel数据
	 */
	@RequiresPermissions("web:yjEquipment:import")
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<YjEquipment> list = ei.getDataList(YjEquipment.class);
			for (YjEquipment yjEquipment : list) {
				try {
					yjEquipmentService.save(yjEquipment);
					successNum++;
				} catch (ConstraintViolationException ex) {
					failureNum++;
				} catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum > 0) {
				failureMsg.insert(0, "，失败 " + failureNum + " 条设备信息记录。");
			}
			addMessage(redirectAttributes, "已成功导入 " + successNum + " 条设备信息记录" + failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入设备信息失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/web/yjEquipment/?repage";
	}

	/**
	 * 下载导入设备信息数据模板
	 */
	@RequiresPermissions("web:yjEquipment:import")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "设备信息数据导入模板.xlsx";
			List<YjEquipment> list = Lists.newArrayList();
			new ExportExcel("设备信息数据", YjEquipment.class, 1).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/web/yjEquipment/?repage";
	}



}
